<template>
  <div>
    <div class="upload" v-if="type === 'img'">
      <el-upload
        ref="upload"
        :action="action"
        :http-request="UploadImage"
        list-type="picture-card"
        :file-list="defaultList"
        :limit="limit"
        :multiple="multiple"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :on-exceed="handleExceed"
        :beforeUpload="onBeforeImgUpload"
        :headers="headers"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog title="查看图片" :visible.sync="dialogVisible" :modal-append-to-body="false">
        <img width="100%" :src="dialogImageUrl" alt />
      </el-dialog>
    </div>

    <div class="upload-file" v-if="type === 'file'">
      <el-upload
        class="upload-demo"
        drag
        :limit="limit"
        :file-list="defaultList"
        :action="action"
        :multiple="multiple"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :on-exceed="handleExceed"
        :beforeUpload="onBeforeUpload"
        :headers="headers"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
      </el-upload>
    </div>
    <el-upload
      v-if="type === 'video'"
      class="upload-demo"
      :action="action"
      :http-request="UploadVideo"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      multiple
      :limit="limit"
      :on-exceed="handleExceed"
      :beforeUpload="onBeforeVideoUpload"
      :on-success="handleSuccess"
      :file-list="defaultList"
      :headers="headers"
    >
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
<!--    <el-progress v-if="type === 'video'" :percentage="0" status="success"></el-progress>-->


    <el-upload
      v-if="type === 'audio'"
      class="upload-demo"
      :action="action"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      multiple
      :limit="limit"
      :on-exceed="handleExceed"
      :beforeUpload="onBeforeUpload"
      :file-list="defaultList"
      :headers="headers"
    >
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
  </div>
</template>

<script>
//腾讯云cos
var COS = require('cos-js-sdk-v5');
import axios from 'axios'
import {post} from '@/framework/http/request'

export default {
  name: 'SiUpload',
  props: {
    //组件类型
    type: {
      type: String,
      default: 'img'
    },
    //文件列表
    fileList: {
      type: Array,
      default() {
        return []
      }
    },
    //限制数量
    limit: {
      type: Number,
      default: 1
    },
    //上传大小,单位为kb
    maxSize: {
      type: Number,
      default: 500
    },
    //接收类型
    accept: {
      type: String,
      default: 'jpg/png/gif/jpeg/mp4/mp3'
    },
    //拼接前缀
    prefix: {
      type: String,
      default: function () {
        // return this.$store.state.prefix
        return 'https://tencentyun-ms-1312352800.cos.ap-guangzhou.myqcloud.com/'
      }
    },
    //多选
    multiple: {
      type: Boolean,
      default: false
    },
    //上传接口路径
    action: {
      type: String,
      default: '/api/attachment/upload'
    }
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      defaultList: [],
      imageUrl: '',
      headers: {
        'Access-Token': localStorage.manager_web_token
      },
      duration: 0,
      percentage:0, //进度条
    }
  },
  created() {
    if (this.fileList.length > 0) {
      this.defaultList = this.fileList.map((s, i) => {
        if (s) {
          let obj = {
            name: s,
            url: this.prefix + s,
            // url: s,
            response: {
              data: s
            }
          }
          return obj
        }
      })
    }
    this.$on('on-form-submit', () => {
      this.$emit('on-transport-file-list', this.defaultList)
    })
    // 关闭弹框时删除图片预览
    this.$on('on-close', () => {
      this.defaultList = []
    })
  },
  methods: {
    handleRemove(file, fileList) {
      this.defaultList = JSON.parse(JSON.stringify(fileList))
      this.$emit('handleRemove')
    },
    handlePreview(file) {
      console.log(file)
    },
    //自定义上传图片
    UploadImage(param){
      console.log('param')
      console.log(param)
      // 初始化实例
      var cos = new COS({
        SecretId: 'AKID3vXu0pNedMnysVsymJZYYHjvpSothDSQ',
        SecretKey: 'i9JDwOaU8UdW9VZMs75lAJAl59wSgeMm',
      })
      //上传图片
      cos.uploadFile({
        Bucket: 'tencentyun-ms-1312352800', /* 必须 */
        Region: 'ap-guangzhou',             /* 存储桶所在地域，必须字段 */
        Key: `/image/${param.file.name}`,               /* 必须 */
        Body: param.file,                   /* 必须 */
        SliceSize: 1024 * 1024 * 5,         /* 触发分块上传的阈值，超过5MB使用分块上传，非必须 */
        onFileFinish: function (err, data, options) {   /* 非必须 */
          // console.log(options.Key + '上传' + (err ? '失败' : '完成'));
        },
      }, function(err, data) {
        console.log(err || data);
        let reg = new RegExp("tencentyun-ms-1312352800.cos.ap-guangzhou.myqcloud.com/","g");
        data.Location = data.Location.replace(reg,"");
        param.onSuccess(data);
      })
    },
    //自定义上传视频
    UploadVideo(param){
      console.log('param')
      console.log(param)
      // // 初始化实例
      // var cos = new COS({
      //   SecretId: 'AKID3vXu0pNedMnysVsymJZYYHjvpSothDSQ',
      //   SecretKey: 'i9JDwOaU8UdW9VZMs75lAJAl59wSgeMm',
      // })
      // //上传视频
      // cos.uploadFile({
      //   Bucket: 'tencentyun-ms-1312352800', /* 必须 */
      //   Region: 'ap-guangzhou',             /* 存储桶所在地域，必须字段 */
      //   Key: `/media/${param.file.name}`,               /* 必须 */
      //   Body: param.file,                   /* 必须 */
      //   SliceSize: 1024 * 1024 * 5,         /* 触发分块上传的阈值，超过5MB使用分块上传，非必须 */
      //   onFileFinish: function (err, data, options) {   /* 非必须 */
      //     // console.log(options.Key + '上传' + (err ? '失败' : '完成'));
      //     console.log(data)
      //     console.log(options)
      //   },
      // }, function(err, data) {
      //   console.log(err || data);
      //   let reg = new RegExp("tencentyun-ms-1312352800.cos.ap-guangzhou.myqcloud.com/","g");
      //   data.Location = data.Location.replace(reg,"");
      //   param.onSuccess(data);
      // })
      const url = ''

      function getSignature() {
        // return axios.post(url).then(function (response) {
        //   return response.data.signature;
        // })
        return 'opzFcNGdzhj04s8JdXi+sbOFGkVzZWNyZXRJZD1BS0lEM3ZYdTBwTmVkTW55c1ZzeW1KWllZSGp2cFNvdGhEU1EmY3VycmVudFRpbWVTdGFtcD0xNjYxMjI0ODU0JmV4cGlyZVRpbWU9MTY2MTgyNDg1NCZyYW5kb209ODg='
      };

      // 通过 import 引入的话，new TcVod(opts) 即可
      // new TcVod.default(opts) 是 script 引入 的用法
      const tcVod = new TcVod.default({
        getSignature: getSignature // 前文中所述的获取上传签名的函数
      })

      const uploader = tcVod.upload({
        mediaFile: param.file, // 媒体文件（视频或音频或图片），类型为 File
      })
      uploader.on('media_progress', function(info) {
        // console.log(info.percent) // 进度
        param.onProgress({percent:info.percent * 100})
      })

      uploader.done().then(function (doneResult) {
        // deal with doneResult
        console.log(doneResult)
        param.onSuccess(doneResult)

      }).catch(function (err) {
        // deal with error
        console.log(err)
      })
    },
    //进度条
    // handleProgress(event,file,fileList){
    //   this.percentage = parseInt((event.loaded / event.total *100).toFixed(0))
    // },
    // 上传成功
    handleSuccess(res, file, fileList) {
      // this.defaultList.push(file);
      // 深拷贝
      console.log(res)
      res.duration = parseFloat(this.duration)
      this.defaultList = JSON.parse(JSON.stringify(fileList))
      // this.defaultList[0].response.data = this.prefix + this.defaultList[0].response.data
      this.$emit('handleSuccess', res)
    },

    // 预览图片
    handlePictureCardPreview(file) {
      console.log(file)
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },

    handleExceed(file, fileList) {
      console.log(file, fileList)
      this.$notify({
        title: '警告',
        message: `最多只能上传${this.limit}个文件`,
        type: 'warning'
      })
    },
    //对图片的格式进行限制
    onBeforeImgUpload(file) {
      // 获取后缀名
      const suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      // 判断是否符合文件大小的限制需求
      const isLt2M = file.size / 1024 / 1024 < this.maxSize
      // 判断是否符合文件类型需求
      let accept = 'jpg/png/gif/jpeg'
      const isLtType = accept.indexOf(suffix) >= 0
      if (!isLtType) {
        this.$message({
          message: `上传文件格式必须为${accept}`,
          type: 'warning'
        })
      }
      console.log(5555,isLt2M)
      if (!isLt2M) {
        this.$message({
          message: `上传文件大小不能超过${this.maxSize}M!`,
          type: 'warning'
        })
      }

      return isLt2M && isLtType
    },
    //对视频的格式进行限制
    onBeforeVideoUpload(file){
      // 获取后缀名
      const suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      // 判断是否符合文件大小的限制需求
      const isLt2M = file.size / 1024 / 1024 < this.maxSize
      // 判断是否符合文件类型需求
      const isLtType = ["video/mp4", "video/ogg", "video/flv", "video/avi", "video/wmv", "video/rmvb", "video/mov"]

      console.log(5555,isLt2M)
      if (!isLt2M) {
        this.$message({
          message: `上传文件大小不能超过${this.maxSize}M!`,
          type: 'warning'
        })
      }

      let correctType = true
      //限制视频格式
      if(isLtType.indexOf(file.type) == -1){
        correctType = false
        this.$message({
          message: '请上传视频格式文件',
          type: 'warning'
        })
      }else{
        correctType = true
      }

      //获取视频时长
      let url = URL.createObjectURL(file);
      let audioElement = new Audio(url);
      let duration;
      let fun = (duration) => {
        this.duration = duration
        console.log(this.duration)
      }
      audioElement.addEventListener("loadedmetadata", function() {
        duration = audioElement.duration; //时长为秒，小数，182.36
        fun(parseFloat(duration).toFixed(1))
      });

      return isLt2M && correctType
    },
    onBeforeUpload(){}
  }
}
</script>

<style scoped>
.upload /deep/ .el-upload-list__item {
  width: 100px;
  height: 100px;
}
.upload /deep/ .el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 106px;
}
</style>
